<template>
  <div class="check-request-tabs">
    <el-card>
      <div class="header-bar">
        <el-input v-model="searchForm.checkName" placeholder="按项目名称查询" style="width: 200px; margin-right: 12px;" />
        <el-select v-model="searchForm.checkType" placeholder="按类型筛选" style="width: 150px; margin-right: 12px;">
          <el-option v-for="item in checkTypeOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleBatchSave">保存选中项</el-button>
      </div>
      <div class="table-wrapper">
        <div class="total-amount">选中项目金额合计: {{ totalAmount }}元</div>
        <div class="register-info" v-if="form.registerId">
          <span class="register-id">挂号ID: {{ form.registerId }}</span>
        </div>
        <el-table 
          :data="checkData" 
          border 
          style="width: 100%;" 
          @selection-change="handleSelectionChange"
          ref="tableRef"
        >
          <el-table-column type="selection" width="50" />
          <el-table-column prop="checkName" label="项目名称" />
          <el-table-column prop="checkType" label="类型" />
          <el-table-column prop="checkPrice" label="单价" width="100" />
        </el-table>
      </div>
    </el-card>

    <!-- 处置信息输入弹窗 -->
    <el-dialog title="填写处置信息" v-model="infoDialogVisible" width="500px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="挂号ID" required>
          <el-input v-model="form.registerId" disabled />
        </el-form-item>
        <el-form-item label="处置目的" required>
          <el-input v-model="form.checkInfo" type="textarea" rows="2" placeholder="请输入处置目的" />
        </el-form-item>
        <el-form-item label="处置部位">
          <el-input v-model="form.checkPosition" placeholder="请输入处置部位" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.checkRemark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="infoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInfo">确认提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const route = useRoute()
const checkData = ref([])
const originalCheckData = ref([])
const searchForm = ref({ checkName: '', checkType: '' })
const checkTypeOptions = ref([])
const selectedItems = ref([])
const form = ref({
  registerId: '',
  checkInfo: '',
  checkPosition: '',
  checkRemark: ''
})
const infoDialogVisible = ref(false)
const tableRef = ref(null)

const totalAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.checkPrice || 0)
  }, 0).toFixed(2)
})

const getRegisterIdFromRoute = () => {
  const patientId = route.query.patientId
  if (patientId) {
    form.value.registerId = patientId
    return true
  } else {
    ElMessage.warning('未从路由参数中获取到挂号ID')
    return false
  }
}

const fetchCheckItems = async () => {
  try {
    const res = await request.get('/medical-technology/chuZhi')
    checkData.value = (res.data || []).map(item => ({
      ...item,
      checkName: item.techName,
      checkType: item.techType,
      checkPrice: item.techPrice
    }))
    originalCheckData.value = [...checkData.value]
    checkTypeOptions.value = Array.from(new Set(checkData.value.map(item => item.checkType)))
  } catch (e) {
    ElMessage.error('获取处置项目失败: ' + (e.message || '未知错误'))
  }
}

const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

const handleSearch = () => {
  let filteredData = [...originalCheckData.value]
  if (searchForm.value.checkName) {
    const keyword = searchForm.value.checkName.toLowerCase()
    filteredData = filteredData.filter(item => 
      item.checkName.toLowerCase().includes(keyword)
    )
  }
  if (searchForm.value.checkType) {
    filteredData = filteredData.filter(item => 
      item.checkType === searchForm.value.checkType
    )
  }
  checkData.value = filteredData
}

const resetSearch = () => {
  searchForm.value = { checkName: '', checkType: '' }
  checkData.value = [...originalCheckData.value]
  if (tableRef.value) tableRef.value.clearSelection()
}

const handleBatchSave = () => {
  if (!getRegisterIdFromRoute()) return
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择处置项目')
    return
  }
  infoDialogVisible.value = true
}

const confirmInfo = async () => {
  if (!form.value.registerId) {
    ElMessage.warning('未获取到有效的挂号ID，请刷新页面重试')
    return
  }
  if (!form.value.checkInfo) {
    ElMessage.warning('请输入处置目的')
    return
  }
  const batchData = selectedItems.value.map(item => ({
    registerId: form.value.registerId,
    medicalTechnologyId: item.id,
    checkInfo: form.value.checkInfo,
    checkPosition: form.value.checkPosition,
    checkRemark: form.value.checkRemark,
    checkState: '已开立',
    techName: item.checkName,
    techPrice: item.checkPrice
  }))
  try {
    await request.post('/check-requests/batch', batchData)
    ElMessage.success(`成功添加 ${selectedItems.value.length} 个处置项目`)
    infoDialogVisible.value = false
    selectedItems.value = []
    resetSearch()
  } catch (e) {
    ElMessage.error('保存失败: ' + (e.message || '未知错误'))
  }
}

onMounted(() => {
  fetchCheckItems()
  getRegisterIdFromRoute()
})
</script>

<style scoped>
.check-request-tabs {
  padding: 12px;
}
.header-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}
.table-wrapper {
  max-width: 100%;
  overflow-x: auto;
}
.total-amount {
  margin-bottom: 10px;
  color: #ff5500;
  font-weight: bold;
}
.register-info {
  margin-bottom: 10px;
  font-size: 14px;
}
.register-id {
  color: #1890ff;
  font-weight: bold;
}
</style>
